const Joi = require('joi');
const path = require('path');
const dotenv = require('dotenv');

dotenv.config({path:path.join(__dirname,"../config.env")})

// define validation for all the env vars
const envVarsSchema = Joi.object({
    NODE_ENV: Joi.string()
        .default('development'),
    SERVER_PORT: Joi.number()
        .default(4040),
    PROJECT_NAME: Joi.string().default('jinmao'),
    PROJECT_ID: Joi.string().default('6228556eab27dc7afa22250e'),
    MONGOOSE_DEBUG: Joi.boolean()
        .when('NODE_ENV', {
            is: Joi.string().equal('development'),
            then: Joi.boolean().default(true),
            otherwise: Joi.boolean().default(false)
        }),
    JWT_SECRET: Joi.string().required()
        .description('JWT Secret required to sign'),
    STATISTIC_RESOURCE: Joi.string().default("/jinmao/02/"),
    MONGO_HOST: Joi.string().required()
        .description('Mongo DB host url'),
    MONGO_PORT: Joi.number()
        .default(27017),
    TEST_SERVER_ADDR:Joi.string().default('localhost:8071')
}).unknown()
    .required();

const { value: envVars, error } = envVarsSchema
    .prefs({ errors: { label: "key" } })
    .validate(process.env);
  
if (error) {
    throw new Error(`Config validation error: ${error.message}`);
  }

const config = {
    projectName: envVars.PROJECT_NAME,
    projectId: envVars.projectId,
    env: envVars.NODE_ENV,
    port: envVars.SERVER_PORT,
    mongooseDebug: envVars.MONGOOSE_DEBUG,
    jwtSecret: envVars.JWT_SECRET,
    frontend: envVars.MERN_FRONTEND,
    statisticResource: envVars.STATISTIC_RESOURCE,
    mongo: {
        host: envVars.MONGO_HOST,
        port: envVars.MONGO_PORT
    },
    testServer:envVars.TEST_SERVER_ADDR
};

module.exports = config;
